﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Clipboard.Tools
{
    public class Settings
    {
        /// <summary>
        /// 读取客户设置
        /// </summary>
        /// <param name="settingName"></param>
        /// <returns></returns>
        public static string GetSettingString(string settingName)
        {
            try
            {
                string? settingString = ConfigurationManager.AppSettings[settingName];
                return settingString ?? string.Empty;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 更新设置
        /// </summary>
        /// <param name="settingName">设置的名称</param>
        /// <param name="valueName">设置的值</param>
        public static void UpdateSettingString(string settingName, string valueName)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                // 如果设置已存在，直接更新
                if (config.AppSettings.Settings[settingName] != null)
                {
                    config.AppSettings.Settings[settingName].Value = valueName;
                }
                else
                {
                    // 如果设置不存在，添加新设置
                    config.AppSettings.Settings.Add(settingName, valueName);
                }

                // 保存配置并刷新
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                // 记录异常信息
                // LogException(ex);  // 如果有日志记录功能的话
                throw new InvalidOperationException($"Failed to update setting '{settingName}'", ex);
            }
        }

    }
}
